package com.atguigu.gmall.item.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author 卡尼奶
 * @Date 2022/5/29 13:19
 * @Version 1.0
 */
@RestController
@RequestMapping("/redis")
public class TestController {

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/lock")
    public String lock(){
        RLock lock = redissonClient.getLock("lock-01");
        //加锁，默认30秒。自动续期
        lock.lock();
        String hello = redisTemplate.opsForValue().get("hello");
        int count = Integer.parseInt(hello);
        count++;
        redisTemplate.opsForValue().set("hello",count+"");
        //解锁
        lock.unlock();
        return "ok";
    }

    @GetMapping("/incr/ss")
    public String test(){
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "1", 10, TimeUnit.SECONDS);
        if (lock){
            String hello = redisTemplate.opsForValue().get("hello");
            int count = Integer.parseInt(hello);
            count++;
            redisTemplate.opsForValue().set("hello",count+"");
            redisTemplate.delete("lock");
        }
        while (!lock){
            lock = redisTemplate.opsForValue().setIfAbsent("lock", "1", 10, TimeUnit.SECONDS);
        }
        return "ok";
    }
}
